import { Toast } from 'antd-mobile';

interface http {
  url: string;
  method?: string;
  headers?: object;
  body?: object;
  setLoading?:(bool : boolean)=> void;
  setResult? :(data : object)=> void;
}

export default function Http({
  url,
  method = 'post',
  headers = {},
  body = {},
  setLoading,
  setResult,
}:http){
  
  if(setLoading){
    
    setLoading(true);
  }
  

  const token = localStorage.getItem('token');
  let defaultHeader:object = {
    'Content-type': 'application/json'
  };
  defaultHeader = token ? {
    ...defaultHeader,
     token
  } : defaultHeader;

  let params:object;
  if(method.toUpperCase() === 'GET'){
    params = {};
  }else {
    params = {
      headers: {
        ...defaultHeader,
        ...headers
      },
      method,
      body: JSON.stringify(body)
    }
  }

  return new Promise((resolve, reject)=>{
    fetch('/api' + url, params)
      .then(res => res.json())
      .then(res => {
        if(res.status === 200){
          resolve(res.data);
          setResult && setResult(res.data);
        }else {
          if(res.status === 1001){
            location.href = '/login?from=' + location.pathname;
            localStorage.clear();
          }
          Toast.fail(res.errMsg);
          reject(res.errMsg);
        }
      })
      .catch(err => {
        Toast.fail(err);
        reject(err);
      })
      .finally(() => {
        
        setLoading && setLoading(false);
      })
  });
}